//
//  FileOperations.swift
//  AriaNgUI
//
//  Created by 石正义 on 2017/9/8.
//  Copyright © 2017年 Shizhy. All rights reserved.
//

import Cocoa

//第一层文件夹名称
let CACHEPATH = "AriaNgCache"

class FileOperations {
    //缓存路径(这里用的沙盒cache文件，非document，可根据需求更改)
    class func getCachePath()->String{
        var cacheDir = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, .userDomainMask, true).first!
        if(!cacheDir.hasSuffix("/")){
            cacheDir += "/"
        }
        cacheDir += CACHEPATH + "/"
        return cacheDir
    }
    
    //获得NSFileManager
    class func getFileManager()->FileManager{
        return FileManager.default
    }
    
    //判断文件夹是否存在
    class func dirExists(dir:String)->Bool{
        return getFileManager().fileExists(atPath: dir)
    }
    
    //判断文件是否存在
    class func fileExists(path:String)->Bool{
        return dirExists(dir: path)
    }
    
    //创建文件夹
    class func createDir(dir:String)->Bool{
        let fileManager = getFileManager()
        do{
            try fileManager.createDirectory(at: NSURL(fileURLWithPath: dir, isDirectory: true) as URL, withIntermediateDirectories: true, attributes: nil)
        }catch{
            return false
        }
        return true
    }
    
    
    /// 删除文件 - 根据文件路径
    ///
    /// - Parameter path: <#path description#>
    /// - Returns: <#return value description#>
    class func deleteFile(path:String)->Bool{
        if(!fileExists(path: path)){
            return true
        }
        let fileManager = getFileManager()
        do{
            try fileManager.removeItem(atPath: path)
        }catch{
            return false
        }
        
        return true
    }
    
    //读取文件 -（根据路径）
    class func readFile(path:String)->NSData?{
        var result:NSData?
        do{
            result = try NSData(contentsOfFile: path, options: NSData.ReadingOptions.uncached)
        }catch{
            return nil
        }
        return result
    }
    
    /// 写文件
    ///
    /// - Parameters:
    ///   - dirName: 文件路径
    ///   - fileName: 文件名称
    ///   - data: 数据data
    /// - Returns: return value description
    class func writeFile(dirName:String,fileName:String,data:NSData)->Bool{
        let filePath = dirName + fileName;
        if !dirExists(dir: filePath) {
            guard createDir(dir: dirName) else{
                return false
            }
        }
        
        return data.write(toFile: filePath, atomically: true)
    }
    
}
